package com.xgkj.diyiketang.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.CommentAdapter;
import com.xgkj.diyiketang.activity.data.DetailFansAdapter;
import com.xgkj.diyiketang.data.CommentInfo;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.SellerInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.AddOrCancleFocusTask;
import com.xgkj.diyiketang.task.CommentListTask;
import com.xgkj.diyiketang.task.FansListTask;
import com.xgkj.diyiketang.task.GetUsemingeTask;
import com.xgkj.diyiketang.task.GetUserDetailTask;
import com.xgkj.diyiketang.task.GetUserInfoTask;
import com.xgkj.diyiketang.task.PublishCommentTask;
import com.xgkj.diyiketang.task.SendFlowerTask;
import com.xgkj.diyiketang.task.ShouCangTask;
import com.xgkj.diyiketang.task.TouPiaoTask;
import com.xgkj.diyiketang.task.VideoDetailTask;
import com.xgkj.diyiketang.task.ZanOrCaiTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.LogUtils;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.weidget.ClearableEditText;
import com.xgkj.diyiketang.weidget.MyCustomListView;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;
import com.xgkj.diyiketang.yizhibo.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

public class GuoxueVideoTwoActivity extends BaseActivity implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener,
        View.OnClickListener {

    private GridView fansGrid;
    private Button pinglunBtn;
    private ClearableEditText cmtContant;
    private DetailFansAdapter dtfansAdapter;
    private MyCustomListView commentList;
    private CommentAdapter cmtAdapter;
    private TextView shang;
    private TextView zan;
    private TextView bofangliang;
    private TextView shoucang;
    private TextView fenxiang;
    //private TextView cai;
    private ImageView userLogo;
    private TextView nickText;
    private TextView signText;
    private Button focusImge;
    private TextView videoInstrText;
    private TextView videoCreatedateText;
    private MyScrollView mySroll;
    private String youkuvid;
    private String userid;
    private String vdid;
    private VideoInfo info;
    // YoukuPlayer实例，进行视频播放控制
//    private YoukuPlayer youkuPlayer;
    private int videoDetailTaskId = -1;
    private int zanTaskId = -1;
    private int caiTaskId = -1;
    private int cancleCaiId = -1;
    private int getUserInfoTaskId = -1;
    private int fanListTaskId = -1;
    private int commentListTaskId = -1;
    private int publishCmtTaskId = -1;
    private int addFocusTaskId = -1;
    private int shoucangTaskId = -1;
    private String zanNum;
    //private String caiNum;
    private String shangNum;
    private String shoucangNum;
    private String fenxiangNum;
    private boolean isZan;
    private boolean isCollect;
    //private boolean isCai;
    private String cmtText;
    private String mSign;
    private String bofangNum;
    private int currentPage = 1;
    private ImageView back;
    private Button moreFans;
    EatShowUserInfo userinfo;
    private ImageView addFocusImg;
    private PopupWindow popWindow;

    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;
    private LinearLayout mFansLayout;
    private TextView mToupiao;
    private String toupiaoNum;
    private int tpTaskId = -1;

    private String share_title;
    private boolean isCanSai;
    private int cancleFocusTaskId = -1;
    private int shareNumTaskId = -1;

    private SellerInfo businessInfo;
    private ImageView sellerlogo;
    private TextView sellerName;
    private TextView sellerType;
    private TextView sellerRenjun;
    private RatingBar rating;
    private RelativeLayout sellerLayout;
    private ImageView fansListDivider;

    private String teacherString;
    private String feeString;
    private String titleString;

    private String songhuaNum;
    private boolean isFirst;
    private int sendflourTaskId = -1;
    protected static final FrameLayout.LayoutParams FULL_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private String play_url;
    private Handler mHandler = new Handler();
    private int width, height;
    private LinearLayout webLayout;
    private int webwidth, webheight;
    private TextView videoScoreText;
    private RelativeLayout linearLayout;
    private String tankuang_type = "";
    /**
     *
     */
    private SurfaceView surfaceView;

    /**
     * surfaceView播放控制
     */
    private SurfaceHolder surfaceHolder;

    /**
     * 播放控制条
     */
    private SeekBar seekBar;

    /**
     * 暂停播放按钮
     */
    private ImageView playButton;

    /**
     * 重新播放按钮
     */
    private ImageView replayButton;

    /**
     * 截图按钮
     */
    private Button screenShotButton;

    /**
     * 改变视频大小button
     */
    private ImageView videoSizeButton;

    /**
     * 加载进度显示条
     */
    private ProgressBar progressBar;

    /**
     * 播放视频
     */
    private MediaPlayer mediaPlayer;

    /**
     * 记录当前播放的位置
     */
    private int playPosition = -1;

    /**
     * seekBar是否自动拖动
     */
    private boolean seekBarAutoFlag = false;

    /**
     * 视频时间显示
     */
    private TextView vedioTiemTextView;

    /**
     * 播放总时间
     */
    private String videoTimeString;

    private long videoTimeLong;

    /**
     * 播放路径
     */
    private String pathString;

    /**
     * 屏幕的宽度和高度
     */
    private int screenWidth, screenHeight;
    private PopupWindow qidaiPop;
    private int useMingeTask = -1;
    private String isMovie;
    private String quotaId = "";
    private String objectId;
    private View inflate;
    private String isUse;
    private int detailTaskId;
    private EatShowUserInfo userInfo;
    private String zhuanyun_jihuo;
    private String parent_jihuo;
    private String z_minge;
    private String p_minge;
    public static boolean used_minge = false;
    private RelativeLayout surface_rl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guoxue_video_two);
        // 获取屏幕的宽度和高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        screenWidth = displayMetrics.widthPixels;
        screenHeight = displayMetrics.heightPixels;
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());  //1104548348
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
        getData();
        initPlayer();
        initViews();
    }

    public void initViews() {
//        String path = null;
//
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            // 存在获取外部文件路径
//            path = Environment.getExternalStorageDirectory().getPath();
//        } else {
//            // 不存在获取内部存储
//            path = Environment.getDataDirectory().getPath();
//        }
        pathString = play_url;
        // 初始化控件
        linearLayout = (RelativeLayout) findViewById(R.id.jindutiao_rl);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surface_rl = (RelativeLayout) findViewById(R.id.surfaceView_rl);
//        int width = mediaPlayer.getVideoWidth();
//        int height = mediaPlayer.getVideoHeight();
//        if (width > screenWidth || height > screenHeight) {
//            // 计算出宽高的倍数
//            float vWidth = (float) width / (float) screenWidth;
//            float vHeight = (float) height / (float) screenHeight;
//            // 获取最大的倍数值，按大数值进行缩放
//            float max = Math.max(vWidth, vHeight);
//            // 计算出缩放大小,取接近的正值
//            width = (int) Math.ceil((float) width / max);
//            height = (int) Math.ceil((float) height / max);
//        }
//        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width,
//                500);
//        surfaceView.setLayoutParams(layoutParams);
//
//        ViewGroup.LayoutParams layoutParams1 = surface_rl.getLayoutParams();
//        layoutParams1.height = height;
//        surface_rl.setLayoutParams(layoutParams1);
//        changeVideoSize(false);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        seekBar = (SeekBar) findViewById(R.id.seekbar);
        videoSizeButton = (ImageView) findViewById(R.id.window_change);
        playButton = (ImageView) findViewById(R.id.vidoe_play);
        replayButton = (ImageView) findViewById(R.id.vidoe_stop);
        vedioTiemTextView = (TextView) findViewById(R.id.textView_showTime);
        // 设置surfaceHolder
        surfaceHolder = surfaceView.getHolder();
        // 设置Holder类型,该类型表示surfaceView自己不管理缓存区,虽然提示过时，但最好还是要设置
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置surface回调
        surfaceHolder.addCallback(new SurfaceCallback());
        mySroll = (MyScrollView) findViewById(R.id.detail_scroll);
        mySroll.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll() {
                getCommentList();
            }
        });
        shang = (TextView) findViewById(R.id.shang);
        zan = (TextView) findViewById(R.id.zan);
        bofangliang = (TextView) findViewById(R.id.bofangliang);
        bofangliang.setOnClickListener(this);
        shoucang = (TextView) findViewById(R.id.detail_shoucang);
        fenxiang = (TextView) findViewById(R.id.fenxiang);
        //cai = (TextView) findViewById(R.id.cai);
        mToupiao = (TextView) findViewById(R.id.toupiao);
        userLogo = (ImageView) findViewById(R.id.user_head_image);
        userLogo.setOnClickListener(this);
        mFansLayout = (LinearLayout) findViewById(R.id.fanslist_layout);
        fansListDivider = (ImageView) findViewById(R.id.fanslist_divider);
        nickText = (TextView) findViewById(R.id.user_name);
        signText = (TextView) findViewById(R.id.user_sign);
        focusImge = (Button) findViewById(R.id.user_focus);
        addFocusImg = (ImageView) findViewById(R.id.addfocus);
        videoInstrText = (TextView) findViewById(R.id.video_instruction);
        videoCreatedateText = (TextView) findViewById(R.id.video_createDate);
        videoScoreText = (TextView) findViewById(R.id.pingfen);
        fansGrid = (GridView) findViewById(R.id.fans_list);
        dtfansAdapter = new DetailFansAdapter(mContext);
        fansGrid.setAdapter(dtfansAdapter);
        commentList = (MyCustomListView) findViewById(R.id.comment_list);
        cmtAdapter = new CommentAdapter(mContext, vdid, 1);
        commentList.setAdapter(cmtAdapter);
        pinglunBtn = (Button) findViewById(R.id.fabiaopinglun);
        pinglunBtn.setOnClickListener(this);
        cmtContant = (ClearableEditText) findViewById(R.id.pinglun);
        back = (ImageView) findViewById(R.id.back);
        moreFans = (Button) findViewById(R.id.more_fans_list);
        moreFans.setOnClickListener(this);
        back.setOnClickListener(this);
        shang.setOnClickListener(this);
        zan.setOnClickListener(this);
        //cai.setOnClickListener(this);
        userLogo.setOnClickListener(this);
        focusImge.setOnClickListener(this);
        addFocusImg.setOnClickListener(this);
        fenxiang.setOnClickListener(this);
        shoucang.setOnClickListener(this);
        mToupiao.setOnClickListener(this);
        sellerlogo = (ImageView) findViewById(R.id.sellerlogo);
        sellerName = (TextView) findViewById(R.id.sellername);
        sellerType = (TextView) findViewById(R.id.sellertype);
        sellerRenjun = (TextView) findViewById(R.id.sellrenjun);
        rating = (RatingBar) findViewById(R.id.ratingbar_Small);
        sellerLayout = (RelativeLayout) findViewById(R.id.seller_layout);
        // 设置拖动监听事件
        seekBar.setOnSeekBarChangeListener(new SeekBarChangeListener());
        // 设置按钮监听事件
        // 重新播放
        replayButton.setOnClickListener(GuoxueVideoTwoActivity.this);
        // 暂停和播放
        playButton.setOnClickListener(GuoxueVideoTwoActivity.this);
        //进度条的显示与否
        surfaceView.setOnClickListener(this);
        // 截图按钮
//        screenShotButton.setOnClickListener(GuoxueVideoTwoActivity.this);
        // 视频大小
        videoSizeButton.setOnClickListener(GuoxueVideoTwoActivity.this);
        initPopWindow();
        getUserDetail();
    }

    private void getData() {
        Intent intent = getIntent();
        vdid = intent.getStringExtra("videoid");
        isMovie = intent.getStringExtra("isMovie");
        if (isMovie.equals("2") || isMovie.equals("3")) {
            String s = "zhuanyun";
            if (qidaiPop == null) {
                getPopwindow(s);
            }
        } else if (isMovie.equals("1")) {
            //弹购买国学会员框
            String s = "guoxue";
            if (qidaiPop == null) {
                getPopwindow(s);
            }
        }
        //info = (VideoInfo) intent.getSerializableExtra("INFO");
        userid = intent.getStringExtra("UID");
        youkuvid = intent.getStringExtra("YOUKUVIDEOID");
        titleString = intent.getStringExtra("TITLE");
        feeString = intent.getStringExtra("FEE");
        isUse = intent.getStringExtra("isUse");
        teacherString = intent.getStringExtra("ZUOZHE");
        if (!ViewUtil.isNull(youkuvid)) {
//            play_url = "http://qiniu.sjmingze.com/%E9%83%91%E9%92%A7%E6%82%9F%E5%85%84.mp4";
            play_url = "http://qiniu.sjmingze.com/" + youkuvid + ".mp4";
        }
        getUserInfo();
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    private void addShareNum() {
        ZanOrCaiTask shareTask = new ZanOrCaiTask(vdid, "1");
        shareTask.addListener(new VideoDetailTaskListener(mContext));
        shareNumTaskId = getEatShowApp().getTaskManager().addTask(shareTask);
    }

    private void getAnchorFansList() {
        FansListTask fansTask = new FansListTask(5, 1, userid);
        fansTask.addListener(new VideoDetailTaskListener(mContext));
        fanListTaskId = getEatShowApp().getTaskManager().addTask(fansTask);
    }
    private void getUserDetail() {
        GetUserDetailTask task = new GetUserDetailTask();
        task.addListener(new VideoDetailTaskListener(mContext));
        detailTaskId = getEatShowApp().getTaskManager().addTask(task);
    }
    private void getUserInfo() {
        GetUserInfoTask uTask = new GetUserInfoTask(userid);
        uTask.addListener(new VideoDetailTaskListener(mContext));
        getUserInfoTaskId = getEatShowApp().getTaskManager().addTask(uTask);
    }

    private void getVideoDetail() {
        VideoDetailTask vdTask = new VideoDetailTask(vdid);
        vdTask.addListener(new VideoDetailTaskListener(this));
        videoDetailTaskId = getEatShowApp().getTaskManager().addTask(vdTask);
    }

    private void getCommentList() {
        if (currentPage == 0) {
            commentList.setNoNextPage();
            return;
        }
        CommentListTask cmtListTask = new CommentListTask(10, currentPage, vdid);
        cmtListTask.addListener(new VideoDetailTaskListener(mContext));
        commentListTaskId = getEatShowApp().getTaskManager().addTask(cmtListTask);
    }

    private void publishComment() {
        //cmtText = cmtContant.getText().toString().trim();
        PublishCommentTask pcTask = new PublishCommentTask(vdid, cmtText, "", "");
        pcTask.addListener(new VideoDetailTaskListener(mContext));
        publishCmtTaskId = getEatShowApp().getTaskManager().addTask(pcTask);
    }

    private void doSendFlour() {
        SendFlowerTask sTask = new SendFlowerTask(1, userid, vdid);
        sTask.addListener(new VideoDetailTaskListener(mContext));
        sendflourTaskId = getEatShowApp().getTaskManager().addTask(sTask);
    }

    //使用观看券
    private void useMnge() {
        if (vdid == null || quotaId == null) {
            return;
        }
        GetUsemingeTask task = new GetUsemingeTask(quotaId, vdid);
        task.addListener(new VideoDetailTaskListener(mContext));
        useMingeTask = getEatShowApp().getTaskManager().addTask(task);
    }

    class VideoDetailTaskListener extends ShowToastTaskEventListener {

        public VideoDetailTaskListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
//            int resultCode = result;
//            PalLog.e("11111111111111111111",resultCode+"");
            if (detailTaskId == taskId){
                if (data != null) {
                    userInfo = (EatShowUserInfo) data;
                    if (userInfo.getList()!=null&&userInfo.getList().size()>0){
                        for (int i = 0; i < userInfo.getList().size(); i++) {
                            String xueyuan = userInfo.getList().get(i).xueyuan;
                            //转运
                            if (xueyuan.equals("3d9513eb1b674af98de226b315765e3f")) {
                                zhuanyun_jihuo = userInfo.getList().get(i).jihuoMinge;
                                z_minge = userInfo.getList().get(i).minge;
                                //父母大学
                            } else {
                                parent_jihuo = userInfo.getList().get(i).jihuoMinge;
                                p_minge = userInfo.getList().get(i).minge;
                            }
                        }
                    }
                }
            }
            if (useMingeTask == taskId) {
//                if (data != null) {
                    if (null != mediaPlayer) {
                        // 正在播放
                        if (Constants.playPosition >= 0) {
                            playButton.setImageResource(R.drawable.playback_icon_stop);
                            mediaPlayer.seekTo(Constants.playPosition);
                            isUse = "1";
                            used_minge = true;
                            mediaPlayer.start();
                            Constants.playPosition = -1;
                        }

//                    }
                }
            }
            if (taskId == videoDetailTaskId) {
                if (data != null) {
                    JSONObject d = (JSONObject) data;
//                        String rcode = d.getString("result");
//                        PalLog.e("1111111111111",rcode);

                    if (d.containsKey("data")) {
                        info = JSON.parseObject(d.getString("data"), VideoInfo.class);
                    }
                    if (d.containsKey("business")) {
                        if (!TextUtils.isEmpty(d.getString("business"))) {
                            businessInfo = JSON.parseObject(d.getString("business"), SellerInfo.class);
                        }
                    }
                }

                if (info != null) {

                    share_title = info.getVideoIntroduction();

                    zanNum = info.getZanNum();
                    //caiNum = info.getCaiNum();
                    shangNum = info.getShangNum();
                    isZan = info.getIsZan();
                    isCollect = info.getIsCollect();
                    //isCai = info.getIsCai();
                    bofangNum = info.getPlayNum();
                    zan.setText(zanNum);
                    songhuaNum = info.getShangNum();

                    bofangliang.setText(songhuaNum);
                    shoucangNum = info.getCollectNum();
                    shoucang.setText(shoucangNum);

                    fenxiangNum = info.getShareNum();
                    fenxiang.setText(fenxiangNum);
                    // cai.setText(caiNum);
                    shang.setText(shangNum);
                    videoInstrText.setText(info.getVideoIntroduction());
                    videoCreatedateText.setText(info.getCreateDate() + "上传");
                    String score = info.getScore();
                    if (ViewUtil.isNull(score) || score.equals("0")) {
                        videoScoreText.setText("--分");
                    } else {
                        videoScoreText.setText(info.getScore() + "分");
                    }
                    if (isCanSai) {
                        mToupiao.setVisibility(View.GONE);
                    } else {
                        toupiaoNum = info.getVoteNum();
                        mToupiao.setText(toupiaoNum);
                    }
                    if (!isCollect) {
                        shoucangtype = "1";
                        shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
                    } else {
                        shoucangtype = "0";
                        shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);
                    }
                    if (!isZan) {
                        zan.setClickable(false);
                        zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
                    } else {
                        zan.setClickable(true);
                        zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_unchecked, 0, 0);
                    }

                    youkuvid = info.getPath();
                    if (youkuvid != null) {
//                        goPlay();
                    }
                }

                if (businessInfo != null && businessInfo.getBusinessId() != null) {
                    sellerLayout.setVisibility(View.VISIBLE);
                    ImageCache.getInstance(mContext).loadBitmapToView(sellerlogo, businessInfo.getBusinessLogo(), new ViewUtil.Size(ViewUtil.dip2px(mContext, 90), ViewUtil.dip2px(mContext, 70)));
                    sellerName.setText(businessInfo.getBusinessName());
                    sellerType.setText(businessInfo.getBusinessType());
                    sellerRenjun.setText("人均￥" + businessInfo.getAverageSpend());
                    try {
                        rating.setRating(Float.parseFloat(businessInfo.getBusinessScore()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sellerLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String fdid = businessInfo.getBusinessId();
                            Intent intent = new Intent(mContext, SellerDetailActivity.class);
                            intent.putExtra("BSUINESSID", fdid);
                            startActivity(intent);
                        }
                    });
                } else {
                    sellerLayout.setVisibility(View.GONE);
                }

                if (getEatShowApp().getmUserInfo() != null) {
                    getAnchorFansList();
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    startActivity(lintent);
                    finish();
                }

            } else if (taskId == zanTaskId) {
                if (info == null) return;
                info.setIsZan(false);
                try {
                    info.setZanNum(String.valueOf((Integer.valueOf(zanNum) + 1)));

                } catch (Exception e) {
                    e.printStackTrace();
                }

                zan.setText(info.getZanNum());
                zan.setClickable(false);
                zan.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.zan_checked, 0, 0);
            } else if (taskId == shareNumTaskId) {
                if (info == null) return;
                try {
                    info.setShareNum(String.valueOf((Integer.valueOf(info.getShareNum()) + 1)));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                fenxiang.setText(info.getShareNum());
            } else if (taskId == tpTaskId) {
                if (info == null) return;
                try {
                    info.setVoteNum(String.valueOf((Integer.valueOf(info.getVoteNum()) + 1)));

                } catch (Exception e) {
                    e.printStackTrace();
                }
                mToupiao.setText(info.getVoteNum());
                ToastUtil.showMessage(GuoxueVideoTwoActivity.this, "投票成功");
            } else if (taskId == shoucangTaskId) {
                if (info == null) return;
                if (!info.getIsCollect()) {
                    info.setIsCollect(true);
                    shoucangtype = "0";
                    info.setCollectNum(String.valueOf((Integer.valueOf(info.getCollectNum()) - 1)));
                    shoucang.setText(info.getCollectNum());

                    shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);
//                    shoucang.setClickable(false);
                    // updateView();

                } else {
                    info.setIsCollect(false);
                    shoucangtype = "1";
                    info.setCollectNum(String.valueOf((Integer.valueOf(info.getCollectNum()) + 1)));
                    shoucang.setText(info.getCollectNum());

                    shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
//                    shoucang.setClickable(false);
                    //updateView();
                }
                shoucang.setClickable(true);

            }
//            else if(taskId ==caiTaskId){
//                info.setIsCai(false);
//                info.setCaiNum(String.valueOf((Integer.valueOf(caiNum) + 1)));
//            }else if(taskId ==cancleCaiId){
//                info.setIsCai(true);
//                info.setCaiNum(String.valueOf((Integer.valueOf(caiNum) - 1)));
//            }
            else if (taskId == getUserInfoTaskId) {
                userinfo = (EatShowUserInfo) data;
                if (userinfo != null) {
                    ImageCache.getInstance(mContext).loadBitmapToView(
                            userLogo,
                            userinfo.getUserLogo(),
                            new ViewUtil.Size(ViewUtil.dip2px(mContext, 60), ViewUtil.dip2px(
                                    mContext, 60)));
//                    if(userinfo.isGame()){
//                        shoucang.setVisibility(View.VISIBLE);
//                    }
//                    nickText.setText(userinfo.getNickName());
//                    signText.setText(userinfo.getUserSign());
                    if (userinfo.getNickName() != null) {
                        try {
                            nickText.setText(URLDecoder.decode(userinfo.getNickName(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    if (userinfo.getUserSign() != null) {
                        try {
                            signText.setText(URLDecoder.decode(userinfo.getUserSign(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                    if (!userinfo.isFocus()) {
                        //focusImge.setText("取消关注");
                        addFocusImg.setImageResource(R.drawable.yiguanzhu);
                        userinfo.setIsFocus(false);
                    } else {
                        //focusImge.setText("关注");
                        addFocusImg.setImageResource(R.drawable.weiguanzhu);
                        userinfo.setIsFocus(true);
                    }

                    if (0 != userinfo.isVip()) ;


                    //getAnchorFansList();
                    getVideoDetail();
                }
            } else if (taskId == fanListTaskId) {
                if (data != null) {
                    List<EatShowUserInfo> list = (List<EatShowUserInfo>) data;
                    if (list != null && list.size() > 0) {
                        dtfansAdapter.clearData();
                        dtfansAdapter.updateData(list);
                        fansListDivider.setVisibility(View.VISIBLE);
                    } else {
                        mFansLayout.setVisibility(View.GONE);
                        fansListDivider.setVisibility(View.GONE);
                    }
//                    getCommentList();
                }
            } else if (taskId == commentListTaskId) {
                if (data != null) {
                    List<CommentInfo> list = (List<CommentInfo>) data;
                    if (currentPage == 1) {
                        cmtAdapter.clearData();
                    }
                    if (list != null && list.size() > 0) {
                        cmtAdapter.updateData(list);
                    }
                    currentPage = result;
                }
            } else if (taskId == publishCmtTaskId) {
                Toast.makeText(mContext, R.string.pinglun_success, Toast.LENGTH_SHORT)
                        .show();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(cmtContant.getWindowToken(), 0);
                cmtContant.setText("");

                currentPage = 1;
                getCommentList();
            } else if (taskId == addFocusTaskId) {
                if (userinfo == null) return;
//                if(info.getIsFocus()){
//                    //focusImge.setText("取消关注");
                addFocusImg.setImageResource(R.drawable.yiguanzhu);
                userinfo.setIsFocus(false);
//                }
//                else{
//                    //focusImge.setText("关注");
//                    addFocusImg.setImageResource(R.drawable.focus_checked);
//                    info.setIsFocus(true);
//                }
            } else if (taskId == cancleFocusTaskId) {
                if (userinfo == null) return;
                addFocusImg.setImageResource(R.drawable.weiguanzhu);
                userinfo.setIsFocus(true);
            } else if (taskId == sendflourTaskId) {
                if (info == null) return;
                try {
                    info.setShangNum(String.valueOf((Integer.valueOf(info.getShangNum()) + 1)));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                bofangliang.setText(info.getShangNum());
                ToastUtil.showMessage(GuoxueVideoTwoActivity.this, "送花成功！");
            }

        }


        private void updateView() {
            shoucang.setClickable(true);
            if (info.getIsCollect()) {
                shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_unchecked, 0, 0);
            } else {
                shoucang.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.shoucang_checked, 0, 0);
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == videoDetailTaskId) {

                int noCode = errorCode;
                if (noCode == 8001032) {
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.no_quanxian), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent gmIntent = new Intent(mContext, GouMaiKeChengActivity.class);
                            gmIntent.putExtra("ZUOZHE", teacherString);
                            gmIntent.putExtra("FEE", feeString);
                            gmIntent.putExtra("TITLE", titleString);
                            gmIntent.putExtra("videoid", vdid);
                            mContext.startActivity(gmIntent);
//                            finish();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
                        }
                    });
                }
                getAnchorFansList();
            } else if (taskId == getUserInfoTaskId) {
                // getUserInfo();
                getVideoDetail();
            } else if (taskId == fanListTaskId) {
                // getAnchorFansList();
            }
        }
    }

    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);
            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)) {
                addShareNum();
            } else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)) {

            }
            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }

    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }
        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine) {
            msg.title = share_title;
        } else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }


    private void shareToWeiBo(String webpage) {
        if (mWeixinShareReceive != null) {
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
//		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // if (hasText) {
        // weiboMessage.mediaObject = getTextObj();
        // }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
//        if (!TextUtils.isEmpty(webpage)) {
//            TextObject textobject = new TextObject();
//            textobject.text = "第一课堂";
//            weiboMessage.textObject = textobject;
//            WebpageObject mediaObject = new WebpageObject();
//            mediaObject.identify = Utility.generateGUID();
//            mediaObject.defaultText = "第一课堂";
//            mediaObject.title = "第一课堂";
//            mediaObject.description = share_title;
//            mediaObject.actionUrl = webpage;
//            if (weiboShareBitmap != null) {
//                mediaObject.setThumbImage(weiboShareBitmap);
//            } else {
//                mediaObject.setThumbImage(BitmapFactory.decodeResource(
//                        getResources(), R.drawable.app_icon));
//            }
//            weiboMessage.mediaObject = mediaObject;
//        }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
            /*
             * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
			 */

        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
//        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
            weibouserid = accessToken.getUid();
        }
//        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//
//            @Override
//            public void onWeiboException(WeiboException arg0) {
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//                weibouserid = newToken.getUid();
////                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//            }
//
//            @Override
//            public void onCancel() {
//            }
//        });


    }

    private boolean checkInput() {
        cmtText = cmtContant.getText().toString().trim();

        if (TextUtils.isEmpty(cmtText)) {
            Toast.makeText(mContext, R.string.no_cmt, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        return true;
    }

    private void showshujuDialog() {
        DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.useshuju), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                youkuPlayer.playVideo(youkuvid);
            }
        }, null);
    }

    public String getTagByUrl(String url) {
        if (url.contains("qq")) {
            return "tvp_fullscreen_button"; // http://m.v.qq.com
        } else if (url.contains("youku")) {
            return "x-zoomin";              // http://www.youku.com
        } else if (url.contains("bilibili")) {
            return "icon-widescreen";       // http://www.bilibili.com/mobile/index.html
        } else if (url.contains("acfun")) {
            return "controller-btn-fullscreen"; //http://m.acfun.tv   无效
        } else if (url.contains("le")) {
            return "hv_ico_screen";         // http://m.le.com  无效
        } else if (url.contains("yk")) {
            return "x-zoomin";
        }
        return "";
    }


    // SurfaceView的callBack
    private class SurfaceCallback implements SurfaceHolder.Callback {
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        public void surfaceCreated(SurfaceHolder holder) {
            // surfaceView被创建
            // 设置播放资源
            playVideo();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // surfaceView销毁,同时销毁mediaPlayer
            if (null != mediaPlayer) {
                mediaPlayer.release();
                mediaPlayer = null;
            }

        }

    }

    /**
     * 播放视频
     */
    private void initPlayer() {
        mediaPlayer = new MediaPlayer();
        // 重置mediaPaly,建议在初始滑mediaplay立即调用。
        mediaPlayer.reset();
        // 设置声音效果
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // 设置播放完成监听
        mediaPlayer.setOnCompletionListener(this);
        // 设置媒体加载完成以后回调函数。
        mediaPlayer.setOnPreparedListener(this);
        // 错误监听回调函数
        mediaPlayer.setOnErrorListener(this);
        // 设置缓存变化监听
        mediaPlayer.setOnBufferingUpdateListener(this);
    }

    public void playVideo() {
        // 初始化MediaPlayer
        Uri uri = Uri.parse("http://qiniu.sjmingze.com/%E9%83%91%E9%92%A7%E6%82%9F%E5%85%84.mp4");
        try {
            // mediaPlayer.reset();
            mediaPlayer.setDataSource(pathString);
            // mediaPlayer.setDataSource(this, uri);
            // mediaPlayer.setDataSource(SurfaceViewTestActivity.this, uri);
            // 设置异步加载视频，包括两种方式 prepare()同步，prepareAsync()异步
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "加载视频错误！", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 视频加载完毕监听
     *
     * @param mp
     */
    private boolean progressBoolean = false;

    @Override
    public void onPrepared(MediaPlayer mp) {
        // 当视频加载完毕以后，隐藏加载进度条
        progressBoolean = true;
        progressBar.setVisibility(View.GONE);
        playButton.setVisibility(View.GONE);
        seekBar.setVisibility(View.GONE);
        linearLayout.setVisibility(View.GONE);
        // 判断是否有保存的播放位置,防止屏幕旋转时，界面被重新构建，播放位置丢失。
//        if (Constants.playPosition >= 0) {
//            mediaPlayer.seekTo(Constants.playPosition);
//            Constants.playPosition = -1;
//            // surfaceHolder.unlockCanvasAndPost(Constants.getCanvas());
//        }
        seekBarAutoFlag = true;
        // 设置控制条,放在加载完成以后设置，防止获取getDuration()错误
        seekBar.setMax(mediaPlayer.getDuration());
        // 设置播放时间
        videoTimeLong = mediaPlayer.getDuration();
        videoTimeString = getShowTime(videoTimeLong);
        vedioTiemTextView.setText("00:00:00/" + videoTimeString);

        // 播放视频
        mediaPlayer.start();
        // 设置显示到屏幕
        mediaPlayer.setDisplay(surfaceHolder);
        // 开启线程 刷新进度条
        new Thread(runnable).start();
        // 设置surfaceView保持在屏幕上
        mediaPlayer.setScreenOnWhilePlaying(true);
        surfaceHolder.setKeepScreenOn(true);

    }

    /**
     * 滑动条变化线程
     */
    private Runnable runnable = new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            // 增加对异常的捕获，防止在判断mediaPlayer.isPlaying的时候，报IllegalStateException异常
            try {
                while (seekBarAutoFlag) {
                    /*
                     * mediaPlayer不为空且处于正在播放状态时，使进度条滚动。
                     * 通过指定类名的方式判断mediaPlayer防止状态发生不一致
                     */

                    if (null != GuoxueVideoTwoActivity.this.mediaPlayer
                            && GuoxueVideoTwoActivity.this.mediaPlayer.isPlaying()) {
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * seekBar拖动监听类
     *
     * @author shenxiaolei
     */
    @SuppressWarnings("unused")
    private class SeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            if (progress >= 0) {
                // 如果是用户手动拖动控件，则设置视频跳转。
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
                // 设置当前播放时间
                vedioTiemTextView.setText(getShowTime(progress) + "/" + videoTimeString);
                if (isUse!=null&&isUse.equals("0")){
                    if (progress > 180000) {
                        if (isMovie.equals("2") || isMovie.equals("3")) {
                            playButton.setImageResource(R.drawable.playback_icon_broadcast);
                            mediaPlayer.pause();
                            if (qidaiPop != null)
                                qidaiPop.showAtLocation(inflate, Gravity.CENTER, 0, 0);
                        } else if (isMovie.equals("1")) {
                            //弹购买国学会员框
                            playButton.setImageResource(R.drawable.playback_icon_broadcast);
                            mediaPlayer.pause();
                            if (qidaiPop != null)
                                qidaiPop.showAtLocation(inflate, Gravity.CENTER, 0, 0);
                        }
                    }
                }

            }
        }

        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub

        }
    }

    //使用观看券弹窗
    private TextView guankanquan, cancle, neirong, title, ok_btn;
    private LinearLayout linearLayout_guankan;

    private void getPopwindow(String tankuang_type) {
        inflate = LayoutInflater.from(this).inflate(R.layout.item_qidai_pop, null);
        ok_btn = (TextView) inflate.findViewById(R.id.ok_btn);
        title = (TextView) inflate.findViewById(R.id.title);
        neirong = (TextView) inflate.findViewById(R.id.neirong);
        linearLayout_guankan = (LinearLayout) inflate.findViewById(R.id.guankanquan);
        guankanquan = (TextView) inflate.findViewById(R.id.use_guankanquan);
        cancle = (TextView) inflate.findViewById(R.id.nouse_guankanquan);
        cancle.setOnClickListener(this);
        guankanquan.setOnClickListener(this);
        ok_btn.setVisibility(View.GONE);
        linearLayout_guankan.setVisibility(View.VISIBLE);
        if (tankuang_type.equals("guoxue")) {
            title.setText("试看结束");
            neirong.setText("购买会员方可观看全部视频");
            guankanquan.setText("去购买");
        } else if (tankuang_type.equals("zhuanyun")) {
            title.setText("试看结束");
            neirong.setText("使用观看券获得观看权限");
            guankanquan.setText("用券观看");
        }

        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        qidaiPop = new PopupWindow(inflate, width - 60, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.5f; //0.0-1.0
//        getWindow().setAttributes(lp);
//        ColorDrawable dw = new ColorDrawable(0x60000000);
        qidaiPop.setBackgroundDrawable(new ColorDrawable());
        qidaiPop.setTouchable(true);
        qidaiPop.setOutsideTouchable(false);
        qidaiPop.setFocusable(true);

    }

    /**
     * 按钮点击事件监听
     */
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok_btn:

                break;
            case R.id.use_guankanquan:
                if (qidaiPop != null) {
                    qidaiPop.dismiss();
                    Constants.playPosition = 0;
                    if (isMovie.equals("1")) {
                        Intent intent = new Intent(this, GuoxueBuyVIPActivity.class);
                        startActivity(intent);
                        finish();
                    } else if (isMovie.equals("2")) {
                        quotaId = "3d9513eb1b674af98de226b315765e3f";
                        if (!TextUtils.isEmpty(zhuanyun_jihuo)&&!TextUtils.isEmpty(z_minge)){
                            if (Integer.parseInt(zhuanyun_jihuo)>0||Integer.parseInt(z_minge)>0){
                                useMnge();
                            }else {
                                Intent intent = new Intent(this,ZhuanyunMoneyActivity.class);
                                intent.putExtra("type","zhuanyun");
                                startActivity(intent);
                                finish();
                            }
                        }else {
                            Intent intent = new Intent(this,ZhuanyunMoneyActivity.class);
                            intent.putExtra("type","zhuanyun");
                            startActivity(intent);
                            finish();
                        }

                    } else if (isMovie.equals("3")) {
                        quotaId = "2737f7a418bf41c998728e6a0f9f253d";
                        if (!TextUtils.isEmpty(parent_jihuo)&&!TextUtils.isEmpty(p_minge)){
                            if (Integer.parseInt(parent_jihuo)>0||Integer.parseInt(p_minge)>0){
                                useMnge();
                            }else {
                                Intent intent = new Intent(this,ZhuanyunMoneyActivity.class);
                                intent.putExtra("type","parent");
                                startActivity(intent);
                                finish();
                            }
                        }else {
                            Intent intent = new Intent(this,ZhuanyunMoneyActivity.class);
                            intent.putExtra("type","parent");
                            startActivity(intent);
                            finish();
                        }

                    }
                }

                break;
            case R.id.nouse_guankanquan:
                if (qidaiPop != null) {
                    mediaPlayer.seekTo(0);
                    seekBar.setProgress(0);
                    Constants.playPosition = -1;
                    qidaiPop.dismiss();
                }
                break;
            case R.id.user_head_image:
//                startActivity(AnchorActivity.getIntent(mContext, userinfo.getUserId()));
                Intent intent = new Intent(mContext, HisDetailActivity.class);
                intent.putExtra("USERID", userid);
                startActivity(intent);
                break;
            case R.id.detail_shoucang:
                if (getEatShowApp().getmUserInfo() != null) {
                    ShouCangTask scTask = new ShouCangTask(vdid, shoucangtype, "");
                    scTask.addListener(new VideoDetailTaskListener(mContext));
                    shoucangTaskId = getEatShowApp().getTaskManager().addTask(scTask);
                    shoucang.setClickable(false);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.zan:
                if (getEatShowApp().getmUserInfo() != null) {
                    ZanOrCaiTask zocTask = null;
                    zocTask = new ZanOrCaiTask(vdid, "0");
                    zocTask.addListener(new VideoDetailTaskListener(mContext));
                    zanTaskId = getEatShowApp().getTaskManager().addTask(zocTask);
                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }

                break;
            case R.id.toupiao:
                if (getEatShowApp().getmUserInfo() != null) {
                    TouPiaoTask tpTask = new TouPiaoTask(userid, "");
                    tpTask.addListener(new VideoDetailTaskListener(mContext));
                    tpTaskId = getEatShowApp().getTaskManager().addTask(tpTask);

                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.fabiaopinglun:
                if (checkInput()) {
                    publishComment();
                    cmtContant.setText(null);
                }

                break;
            case R.id.addfocus:
                //addGuanZhu();
                if (!userinfo.isFocus()) {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(userid, "1");
                    task.addListener(new VideoDetailTaskListener(mContext));
                    cancleFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                } else {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(userid, "0");
                    task.addListener(new VideoDetailTaskListener(mContext));
                    addFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                }
                break;

            case R.id.back:
                if (mediaPlayer!=null){
                    mediaPlayer.stop();

                }
                finish();
                break;
            case R.id.more_fans_list:
                Intent moreIntent = new Intent(mContext, FansListActivity.class);
                moreIntent.putExtra("UserId", userid);
                startActivity(moreIntent);
                break;
            case R.id.fenxiang:
                if (getEatShowApp().getmUserInfo() != null) {
                    popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                } else {
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                    finish();
                }
                break;
            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                //
                String uuid = userid;

                String vid = vdid;

                String path = youkuvid;

                String sharepath2 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid + "&videoId=" + vid + "&videoPath=" + path + "";
                shareToWeiXin(sharepath2, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
                //shareToWeiXin(info.getPpnsharehtmlurl(), false);
                //String sharepath = "http://115.28.236.67:8096/classroom/class_video.html?userid=afc2d38e69ad458dbe029bdd7126e501&videoid=4c9108b8bb47407fb2a6d42c1299a9f9&videopath=XMTQ3MjE3NTIwNA";
                String uuid2 = userid;
                String vid2 = vdid;
                String path2 = youkuvid;
                String sharepath = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid2 + "&videoId=" + vid2 + "&videoPath=" + path2 + "";
                shareToWeiXin(sharepath, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                //shareToWeiBo(info.getPpnsharehtmlurl());
                String uuid3 = userid;
                String vid3 = vdid;
                String path3 = youkuvid;
                String sharepath3 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid3 + "&videoId=" + vid3 + "&videoPath=" + path3 + "";
                shareToWeiBo(sharepath3);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:
                String uuid5 = userid;
                String vid5 = vdid;
                String path5 = youkuvid;
                String sharepath5 = "http://115.28.236.67:8096/classroom/class_video.html?userId=" + uuid5 + "&videoId=" + vid5 + "&videoPath=" + path5 + "";
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
                weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);

                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, sharepath5);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com/diyiketangImage/diyiketang_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;

            case R.id.bofangliang:
                isFirst = EatShowSetting.getInstance(mContext).getIsFirstSend();
                if (isFirst) {
//                    ToastUtil.showMessage(mContent,"第一次");
                    EatShowSetting.getInstance(mContext).setIsFirstSend(false);
                    DialogUtil.createDialog(mContext, -1, getString(R.string.prompt), getString(R.string.if_send_flour), getString(R.string.ok), getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            doSendFlour();
                        }
                    }, null);

                } else {
//                    ToastUtil.showMessage(mContent,"不是第一次");
                    doSendFlour();
                }
                break;
            case R.id.vidoe_stop: // 重新播放// 重新播放
                if (null != mediaPlayer) {
                    // MediaPlayer和进度条都跳转到开始位置
                    mediaPlayer.seekTo(0);
                    seekBar.setProgress(0);
                    // 如果不处于播放状态，则开始播放
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                    }
                } else {
                    // 为空则重新设置mediaPlayer
                    playVideo();
                }
                break;
            case R.id.vidoe_play:// 播放、暂停按钮
                if (null != mediaPlayer) {
                    // 正在播放
                    if (mediaPlayer.isPlaying()) {
                        playButton.setImageResource(R.drawable.playback_icon_broadcast);
                        Constants.playPosition = mediaPlayer.getCurrentPosition();
                        mediaPlayer.pause();
                    } else {
                        if (Constants.playPosition >= 0) {
                            playButton.setImageResource(R.drawable.playback_icon_stop);
                            if (Constants.playPosition - 5000 > 0) {
                                mediaPlayer.seekTo(Constants.playPosition - 5000);
                            } else {
                                mediaPlayer.seekTo(Constants.playPosition);
                            }
                            mediaPlayer.start();
                            Constants.playPosition = -1;
                        }
                    }
                } else {
                    // 为空则重新设置mediaPlayer
                    playVideo();
                }
                break;
            case R.id.surfaceView:
                //显示进度条
                if (progressBoolean) {
                    linearLayout.setVisibility(View.VISIBLE);
                    playButton.setVisibility(View.VISIBLE);
                    seekBar.setVisibility(View.VISIBLE);
                    progressBoolean = false;
                } else {
                    linearLayout.setVisibility(View.GONE);
                    playButton.setVisibility(View.GONE);
                    seekBar.setVisibility(View.GONE);
                    progressBoolean = true;
                }
                break;
            case R.id.window_change:
                // 调用改变大小的方法
                if (videoSize) {
                    videoSize = false;
                    changeVideoSize(videoSize);
                } else {
                    videoSize = true;
                    changeVideoSize(videoSize);
                }
                break;
        }
        // TODO Auto-generated method stub


    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            addShareNum();

        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };

    private boolean videoSize = false;

    /**
     * 播放完毕监听
     *
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        // 设置seeKbar跳转到最后位置
        seekBar.setProgress(Integer.parseInt(String.valueOf(videoTimeLong)));
        // 设置播放标记为false
        seekBarAutoFlag = false;
    }

    /**
     * 视频缓存大小监听,当视频播放以后 在started状态会调用
     */
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        // TODO Auto-generated method stub
        // percent 表示缓存加载进度，0为没开始，100表示加载完成，在加载完成以后也会一直调用该方法
        LogUtils.e("text", "onBufferingUpdate-->" + percent);
        // 可以根据大小的变化来
    }

    /**
     * 错误监听
     *
     * @param mp
     * @param what
     * @param extra
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                Toast.makeText(this, "MEDIA_ERROR_UNKNOWN", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                Toast.makeText(this, "MEDIA_ERROR_SERVER_DIED", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

        switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                Toast.makeText(this, "MEDIA_ERROR_IO", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                Toast.makeText(this, "MEDIA_ERROR_MALFORMED", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                Toast.makeText(this, "MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK",
                        Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                Toast.makeText(this, "MEDIA_ERROR_TIMED_OUT", Toast.LENGTH_SHORT).show();
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                Toast.makeText(this, "MEDIA_ERROR_UNSUPPORTED", Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }

    /**
     * 从暂停中恢复
     */
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        // 判断播放位置
        if (Constants.playPosition >= 0) {
            if (null != mediaPlayer) {
                seekBarAutoFlag = true;
                mediaPlayer.seekTo(Constants.playPosition);
                mediaPlayer.start();
            } else {
                playVideo();
            }

        }
    }

    /**
     * 页面处于暂停状态
     */
    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                Constants.playPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.pause();
                seekBarAutoFlag = false;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 发生屏幕旋转时调用
     */
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        if (null != mediaPlayer) {
            // 保存播放位置
            Constants.playPosition = mediaPlayer.getCurrentPosition();
        }
    }

    /**
     * 屏幕旋转完成时调用
     */
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);

    }

    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 屏幕销毁时调用
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 由于MediaPlay非常占用资源，所以建议屏幕当前activity销毁时，则直接销毁
        try {
            if (null != GuoxueVideoTwoActivity.this.mediaPlayer) {
                // 提前标志为false,防止在视频停止时，线程仍在运行。
                seekBarAutoFlag = false;
                // 如果正在播放，则停止。
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer = null;
                }
                Constants.playPosition = -1;
                // 释放mediaPlayer
                GuoxueVideoTwoActivity.this.mediaPlayer.release();
                GuoxueVideoTwoActivity.this.mediaPlayer = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 转换播放时间
     *
     * @param milliseconds 传入毫秒值
     * @return 返回 hh:mm:ss或mm:ss格式的数据
     */
    @SuppressLint("SimpleDateFormat")
    public String getShowTime(long milliseconds) {
        // 获取日历函数
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliseconds);
        SimpleDateFormat dateFormat = null;
        // 判断是否大于60分钟，如果大于就显示小时。设置日期格式
        if (milliseconds / 60000 > 60) {
            dateFormat = new SimpleDateFormat("hh:mm:ss");
        } else {
            dateFormat = new SimpleDateFormat("mm:ss");
        }
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 保存视频截图.该方法只能支持本地视频文件
     *
     * @param time 视频当前位置
     */
    public void savaScreenShot(long time) {
        // 标记是否保存成功
        boolean isSave = false;
        // 获取文件路径
        String path = null;
        // 文件名称
        String fileName = null;
        if (time >= 0) {
            try {
                Uri uri = Uri
                        .parse("http://183.61.13.14/vmind.qqvideo.tc.qq.com/x0200hkt1cg.p202.1.mp4");
                MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                mediaMetadataRetriever.setDataSource(pathString);
                // 获取视频的播放总时长单位为毫秒
                String timeString = mediaMetadataRetriever
                        .extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                // 转换格式为微秒
                long timelong = Long.parseLong(timeString) * 1000;
                // 计算当前视频截取的位置
                long index = (time * timelong) / mediaPlayer.getDuration();
                // 获取当前视频指定位置的截图,时间参数的单位是微秒,做了*1000处理
                // 第二个参数为指定位置，意思接近的位置截图
                Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(time * 1000,
                        MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                // 释放资源
                mediaMetadataRetriever.release();
                // 判断外部设备SD卡是否存在
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 存在获取外部文件路径
                    path = Environment.getExternalStorageDirectory().getPath();
                } else {
                    // 不存在获取内部存储
                    path = Environment.getDataDirectory().getPath();
                }
                // 设置文件名称 ，以事件毫秒为名称
                fileName = Calendar.getInstance().getTimeInMillis() + ".jpg";
                // 设置保存文件
                File file = new File(path + "/shen/" + fileName);

                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                isSave = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 保存成功以后，展示图片
            if (isSave) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                imageView.setImageBitmap(BitmapFactory.decodeFile(path + "/shen/" + fileName));
                new AlertDialog.Builder(this).setView(imageView).show();
            }
        }

    }

    /**
     * 改变视频的显示大小，全屏，窗口，内容
     */
    public void changeVideoSize(boolean s) {
        // 改变视频大小
//        String videoSizeString = videoSizeButton.getText().toString();

        // 获取视频的宽度和高度
        int width = mediaPlayer.getVideoWidth();
        int height = mediaPlayer.getVideoHeight();
        // 如果按钮文字为窗口则设置为窗口模式
//        if ("窗口".equals(videoSizeString)) {
        if (!s) {
            /*
             * 如果为全屏模式则改为适应内容的，前提是视频宽高小于屏幕宽高，如果大于宽高 我们要做缩放
             * 如果视频的宽高度有一方不满足我们就要进行缩放. 如果视频的大小都满足就直接设置并居中显示。
             */
            GuoxueVideoTwoActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            if (width > screenWidth || height > screenHeight) {
                // 计算出宽高的倍数
                float vWidth = (float) width / (float) screenWidth;
                float vHeight = (float) height / (float) screenHeight;
                // 获取最大的倍数值，按大数值进行缩放
                float max = Math.max(vWidth, vHeight);
                // 计算出缩放大小,取接近的正值
                width = (int) Math.ceil((float) width / max);
                height = (int) Math.ceil((float) height / max);
            }
            // 设置SurfaceView的大小并居中显示
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width,
                    ViewUtil.dip2px(mContext,240));
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            surfaceView.setLayoutParams(layoutParams);
            ViewGroup.LayoutParams layoutParams1 = surface_rl.getLayoutParams();
            layoutParams1.height = ViewUtil.dip2px(mContext,220);
            surface_rl.setLayoutParams(layoutParams1);
//            videoSizeButton.setText("全屏");
        } else {
            // 设置全屏
            // 设置SurfaceView的大小并居中显示
            GuoxueVideoTwoActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int widthPixels = dm.widthPixels;
            int heightPixels = dm.heightPixels;
            ViewGroup.MarginLayoutParams margin = new ViewGroup.MarginLayoutParams(
                    surfaceView.getLayoutParams());
            margin.setMargins(0,0,0,0);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin);
            layoutParams.height = widthPixels;
            layoutParams.width = heightPixels;
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            surfaceView.setLayoutParams(layoutParams);
            ViewGroup.LayoutParams layoutParams1 = surface_rl.getLayoutParams();
            layoutParams1.height = screenWidth-50;
            surface_rl.setLayoutParams(layoutParams1);
//            videoSizeButton.setText("窗口");
        }

//        DisplayMetrics dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        mSurfaceViewWidth = dm.widthPixels;
//        mSurfaceViewHeight = dm.heightPixels;
//        if (width > height) {
//            // 竖屏录制的视频，调节其上下的空余
//
//            int w = mSurfaceViewHeight * width / height;
//            int margin = (mSurfaceViewWidth - w) / 2;
//            Logger.d(TAG, "margin:" + margin);
//            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
//                    RelativeLayout.LayoutParams.MATCH_PARENT,
//                    RelativeLayout.LayoutParams.MATCH_PARENT);
//            lp.setMargins(margin, 0, margin, 0);
//            mSurfaceView.setLayoutParams(lp);
//        } else {
//            // 横屏录制的视频，调节其左右的空余
//
//            int h = mSurfaceViewWidth * height / width;
//            int margin = (mSurfaceViewHeight - h) / 2;
//            Logger.d(TAG, "margin:" + margin);
//            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
//                    RelativeLayout.LayoutParams.MATCH_PARENT,
//                    RelativeLayout.LayoutParams.MATCH_PARENT);
//            lp.setMargins(0, margin, 0, margin);
//            mSurfaceView.setLayoutParams(lp);
//        }
    }
}
